<template>
  <div class="app-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">业主详细信息</span>
      </template>
    </el-page-header>

    <el-card class="box-card" style="margin-top: 20px;" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>业主信息概览</span>
        </div>
      </template>

      <div v-if="form.ownerId">
        <!-- 标签页 -->
        <el-tabs v-model="activeTab" type="border-card" class="info-tabs">
          <!-- 基本信息标签页 -->
          <el-tab-pane label="基本信息" name="basic">
            <!-- 基本信息 -->
            <div class="info-section">
              <div class="section-title">基本信息</div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="序号">{{ form.ownerId || '-' }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ form.nickName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ form.userName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ form.phonenumber || '-' }}</el-descriptions-item>
                <el-descriptions-item label="身份证号">{{ form.idCard || '-' }}</el-descriptions-item>
                <el-descriptions-item label="出生日期">{{ formatDate(form.birthDate) || '-' }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ formatGender(form.gender) || '-' }}</el-descriptions-item>
                <el-descriptions-item label="民族">{{ form.nation || '-' }}</el-descriptions-item>
                <el-descriptions-item label="婚姻状态">{{ form.maritalStatus || '-' }}</el-descriptions-item>
                <el-descriptions-item label="户口类型">{{ form.householdType || '-' }}</el-descriptions-item>
                <el-descriptions-item label="现住地址" :span="2">{{ form.currentAddress || '-' }}</el-descriptions-item>
                <el-descriptions-item label="类型">{{ form.type || '业主' }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 分隔线 -->
            <div class="divider"></div>

            <!-- 紧急联系人 -->
            <div class="info-section emergency-section">
              <div class="section-title emergency-title">
                <i class="el-icon-warning"></i>
                紧急联系人
              </div>
              <el-descriptions :column="2" border class="emergency-descriptions">
                <el-descriptions-item label="姓名">{{ form.emergencyContactName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="关系">{{ form.emergencyContactRelation || '-' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ form.emergencyContactPhone || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <!-- 楼宇信息标签页 -->
          <el-tab-pane label="房屋信息" name="building">
            <BuildingCard
                v-if="buildingData && Object.keys(buildingData).length > 0"
                :building-data="buildingData"
            />
            <el-empty v-else description="暂无房屋信息" />
          </el-tab-pane>

          <!-- 成员信息标签页 -->
          <el-tab-pane label="成员信息" name="member">
            <ResidentCard
                v-if="residentData && residentData.length > 0"
                :resident-data="residentData"
            />
            <el-empty v-else description="暂无成员信息" />
          </el-tab-pane>


          <!-- 储藏室标签页 -->
          <el-tab-pane label="储藏室" name="storage">
            <StorageRoomCard
                v-if="storageRoomData && storageRoomData.length > 0"
                :storage-room-data="storageRoomData"
            />
            <el-empty v-else description="暂无储藏室信息" />
          </el-tab-pane>

          <!-- 车位信息标签页 -->
          <!-- 车位信息标签页 -->
          <el-tab-pane label="车位信息" name="parking">
            <ParkingSpaceCard
                v-if="parkingSpaceData && parkingSpaceData.length > 0"
                :parking-space-data="parkingSpaceData"
            />
            <el-empty v-else description="暂无车位信息" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <el-empty v-else description="未找到业主信息" />
    </el-card>
  </div>
</template>

<script setup name="OwnerMessage">
import { ref, onMounted, watch, getCurrentInstance } from 'vue'
import { getDetail } from "@/api/owner/owner.js"
import { getBuildingByOwnerId } from "@/api/owner/building.js"
import { useRoute } from 'vue-router'
import { getResidentByOwnerId } from "@/api/owner/resident.js"
import StorageRoomCard from './storageRoomMessage.vue'
import { getStorageRoomByOwnerId } from "@/api/owner/storageRoom.js"
import { getParkingSpaceByOwnerId } from "@/api/owner/parkingSpace.js"
import ParkingSpaceCard from './parkingSpaceMessage.vue'
import BuildingCard from './buildingMessage.vue'
import ResidentCard from './residentMessage.vue'



const route = useRoute()
const { proxy } = getCurrentInstance()

const form = ref({})
const loading = ref(false)
const buildingData = ref({})
const activeTab = ref('basic') // 默认激活基本信息标签页
const residentData = ref([])
const storageRoomData = ref([])
const parkingSpaceData = ref([])

// 获取业主详情
const fetchOwnerDetail = (ownerId) => {
  if (!ownerId) {
    proxy.$modal.msgError('未找到业主ID')
    return
  }

  loading.value = true
  form.value = {} // 清空旧数据

  console.log('正在获取业主详情，ID:', ownerId)

  getDetail(ownerId).then(response => {
    if (response.code === 200) {
      form.value = response.data
      console.log('获取到业主数据:', response.data)
      // 获取楼宇信息
      fetchBuildingInfo(ownerId)
      // 获取住户信息
      fetchResidentInfo(ownerId)
      // 获取储藏室信息
      fetchStorageRoomInfo(ownerId)
      // 获取车位信息
      fetchParkingSpaceInfo(ownerId)
    } else {
      proxy.$modal.msgError(response.msg || '获取业主信息失败')
      loading.value = false
    }
  }).catch(error => {
    console.error('获取业主信息失败:', error)
    proxy.$modal.msgError(error.response.data.msg||'获取业主信息失败')
    loading.value = false
  })
}

// 获取楼宇信息
const fetchBuildingInfo = async (ownerId) => {
  try {
    const response = await getBuildingByOwnerId(ownerId)
    if (response.code === 200) {
      buildingData.value = response.data
      console.log('获取到楼宇数据:', response.data)
    } else {
      console.warn('未找到楼宇信息')
    }
  } catch (error) {
    console.error('获取楼宇信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取住户信息
const fetchResidentInfo = async (ownerId) => {
  try {
    const response = await getResidentByOwnerId(ownerId)
    if (response.code === 200) {
      residentData.value = response.data
      console.log('获取到住户数据:', response.data)
    } else {
      console.warn('未找到住户信息')
      residentData.value = []
    }
  } catch (error) {
    console.error('获取住户信息失败:', error)
    residentData.value = []
  }
}

// 获取储藏室信息
const fetchStorageRoomInfo = async (ownerId) => {
  try {
    const response = await getStorageRoomByOwnerId(ownerId)
    if (response.code === 200) {
      storageRoomData.value = response.data
      console.log('获取到储藏室数据:', response.data)
    } else {
      console.warn('未找到储藏室信息')
      storageRoomData.value = []
    }
  } catch (error) {
    console.error('获取储藏室信息失败:', error)
    storageRoomData.value = []
  }
}

// 获取车位信息
const fetchParkingSpaceInfo = async (ownerId) => {
  try {
    const response = await getParkingSpaceByOwnerId(ownerId)
    if (response.code === 200) {
      parkingSpaceData.value = response.data
      console.log('获取到车位数据:', response.data)
    } else {
      console.warn('未找到车位信息')
      parkingSpaceData.value = []
    }
  } catch (error) {
    console.error('获取车位信息失败:', error)
    parkingSpaceData.value = []
  }
}

// 性别格式化
const formatGender = (gender) => {
  if (gender === '0' || gender === 0) return '男'
  if (gender === '1' || gender === 1) return '女'
  return gender || '-'
}

// 日期格式化 - 将 ISO 8601 格式转换为 YYYY-MM-DD
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateString
  }
}

// 返回上一页
const goBack = () => {
  proxy.$tab.closePage()
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return '-'
  try {
    return proxy.$parseTime(time, '{y}-{m}-{d}')
  } catch (e) {
    return time
  }
}

// 监听路由参数变化
watch(
    () => route.query.id || route.params.id,
    (newId, oldId) => {
      console.log('路由参数变化，旧ID:', oldId, '新ID:', newId)
      if (newId && newId !== oldId) {
        fetchOwnerDetail(newId)
      }
    },
    { immediate: true }
)

// 组件挂载时执行
onMounted(() => {
  console.log('业主详情页面已挂载')
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.box-card {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.info-tabs {
  :deep(.el-tabs__header) {
    background-color: #f8f9fa;
  }

  :deep(.el-tabs__content) {
    padding: 30px;
    min-height: 400px;
  }

  :deep(.el-tab-pane) {
    padding: 0;
  }
}

.info-section {
  margin-bottom: 30px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #409eff;
  border-left: 4px solid #409eff;
  padding-left: 12px;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 紧急联系人特殊样式 - 只设置标题为红色 */
.emergency-section {
  .emergency-title {
    color: #f56c6c;
    border-left-color: #f56c6c;

    .el-icon-warning {
      color: #f56c6c;
    }
  }
}

.divider {
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, #e4e7ed 50%, transparent 100%);
  margin: 25px 0;
}

:deep(.el-descriptions) {
  margin-bottom: 0;
}

:deep(.el-descriptions__label) {
  width: 100px;
  background-color: #f5f7fa;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  font-weight: 400;
}

:deep(.el-descriptions__table) {
  // 增加行高，让内容更宽松
  .el-descriptions-row {
    td {
      padding: 12px 10px;
    }
  }
}
</style>
